<template>
  <div class="container">
    <h3>vue+openlayers: 设置不同坐标点，用不同颜色区分</h3>
    <div id="vue-openlayers" ref="map" class="map-x"></div>
  </div>
</template>

<script>
import 'ol/ol.css';
import {Map,View} from 'ol'
import Tile from 'ol/layer/Tile'
import XYZ from "ol/source/XYZ";
import VectorLayer from 'ol/layer/Vector'; // 矢量图层
import VectorSource from 'ol/source/Vector'; // 矢量数据源
import { Style, Storke, Icon } from 'ol/style';
import Feature from 'ol/Feature'; // 要素
import { Point, LineString, Polygon } from 'ol/geom'; // 点要素
export default {
  data() {
    return {
      map: null
    }
  },

  mounted() {
    this.initMap();
  },

  methods: {
    diffPointColorSource() {
      let rome = new Feature({
        geometry: new Point([12.5, 41.9]) // 这里的坐标是梵蒂冈的坐标
      })
      let london = new Feature({
        geometry: new Point([-0.12755, 51.507222]), // 这里的坐标是伦敦的坐标
      })
      let madrid = new Feature({
        geometry: new Point([-3.683333, 40.4]), // 这里的坐标是马德里的坐标
      })

      rome.setStyle(new Style({
        image: new Icon({
          color: '#f00',
          crossOrigin: 'anonymous', // 跨域
          src: require('@/assets/icon/love.svg')
        })
      }))

      london.setStyle(new Style({
        image: new Icon({
          color: 'Orange',
          crossOrigin: 'anonymous', // 跨域
          src: require('@/assets/icon/love.svg')
        })
      }))

      madrid.setStyle(new Style({
        image: new Icon({
          color: [0, 0, 255, 0.8], // rgba
          crossOrigin: 'anonymous', // 跨域
          src: require('@/assets/icon/love.svg')
        })
      }))

      let vectorSource = new VectorSource({
        features: [rome, london, madrid]
      }) // 矢量数据源
      return vectorSource
    },

    initMap() {
      let raster = new Tile({
        source: new XYZ({
          url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7'
        })
      })
      let vector = new VectorLayer({
        source: this.diffPointColorSource()
      })
      this.map = new Map({
        target: this.$refs.map,
        layers: [raster, vector],
        view: new View({
          projection: 'EPSG:4326',
          center: [12.5, 41.9],
          zoom: 4
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
    width: 840px;
    height: 550px;
    margin: 50px auto;
    border: 1px solid #ccc;
    #vue-openlayers {
      width: 800px;
      height: 420px;
      margin: 0 auto;
      border: 1px solid #42b983;
      position: relative;
    }
  }
</style>
